package cn.lijiajia3515.cairo.captcha.image;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.script.ScriptUtil;
import cn.lijiajia3515.cairo.captcha.CaptchaArgs;
import lombok.Getter;
import lombok.Setter;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;

import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 算数字符串生成器
 */
public class ArithmeticImageCaptchaHandler extends ImageCaptchaHandler {


    /**
     * 最小值
     */
    @Setter
    @Getter
    private int minNum = 1;

    /**
     * 最大值
     */
    @Setter
    @Getter
    private int maxNum = 11;

    /**
     * 数量
     */
    @Setter
    @Getter
    private int length = 3;

    @Override
    protected Tuple2<String, String> getImageCaptchaStr(CaptchaArgs args) {
        String script = IntStream.range(0, length).mapToObj(d -> String.valueOf(RandomUtil.randomInt(minNum, maxNum))).collect(Collectors.joining(calc()));
        String code = String.valueOf(ScriptUtil.eval(script));
        String imageStr = script.concat("=?").replaceAll("\\*", "x");
        return Tuples.of(code, imageStr);
    }

    public String calc() {
        switch (RandomUtil.randomInt(0, 4)) {
            case 1:
                return "-";
            case 2:
                return "*";
            default:
                return "+";
        }
    }


}
